<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\Exception;
use think\exception\ValidateException;

use \PHPExcel_Style_Color;
use \PHPExcel_Style_Alignment;
use \PHPExcel_style_Fill;
use \PHPExcel_Style_Border;

use service\JsonService as Json;
use service\ChoiceService as Choice;
use app\admin\controller\BaseController;

use app\common\model\User;
use app\common\model\UserResume;
use app\common\model\ResumeRecord;
use app\common\model\OkrRecord;
use app\common\model\Message;
use app\common\model\Job;
use app\common\model\Project;
use app\common\model\ResumeEducation;
use app\common\model\ResumeRound;
use app\common\model\ResumeFieldDepot;
use app\common\model\UserCompany;
use app\common\model\ResumeHref;

use app\common\validate\ResumeValidate;

class ResumeController extends BaseController
{
    /**
     * 获取简历列表
     */
    public function getResumeList()
    {
        $page       = Request()->param('page', 1);
        $expectJobs = Request()->param('expect_jobs', '');
        $age        = Request()->param('age', '');
        $sex        = Request()->param('sex', '');
        $education  = Request()->param('education', '');
        // $jobTime    = Request()->param('job_time', '');
        $wage       = Request()->param('wage', '');
        $name       = Request()->param('name', '');

        $where[] = ['is_staff', '=', 0];
        $where[] = ['name', '<>', ''];

        if(!empty($expectJobs)) $where[] = ['expect_jobs', 'like', '%' . $expectJobs . '%'];
        if(!empty($education)) $where[] = ['education', '=', $education];
        if(!empty($sex)) $where[] = ['sex', '=', $sex];
        if(!empty($name)) $where[] = ['name', 'like', '%' . $name . '%'];

        if(!empty($age)){
            list($ageLow, $ageHigh) = explode('-', $age);

            if($ageLow > 0) $where[]  = ['age', '<=', $ageLow];
            if($ageHigh > 0) $where[] = ['age', '>=', $ageHigh];
        }

        // if(!empty($jobTime)){
        //     list($jobTimeLow, $jobTimeHigh) = explode('-', $jobTime);

        //     if($jobTimeLow > 0) $where[]  = ['job_time', '<=', strtotime("-" . $jobTimeLow . " year")];
        //     if($jobTimeHigh > 0) $where[] = ['job_time', '>=', strtotime("-" . $jobTimeHigh . " year")];
        // }

        if(!empty($wage)){
            list($wageLow, $wageHigh) = explode('-', $wage);

            if($wageLow > 0) $where[]  = ['wage_low', '>=', $wageLow * 1000];
            if($wageHigh > 0) $where[] = ['wage_low', '<=', $wageHigh * 1000];
        }

        $list = UserResume::getList($where, 1, $page, 20, '*', 'claim_user_id, create_time DESC');
        if($list === false) return Json::fail('暂无数据');

        $edu       = [0 => '其他', 1 => '小学', 2 => '初中', 3 => '高中', 4 => '大专', 5 => '本科', 6 => '硕士', 7 => '博士'];
        $sexs      = [1 => '男', 2 => '女'];
        $jobStatus = [1 => '在职', 2 => '离职'];

        foreach($list as &$info){
            $avatars = User::getVal(['id' => $info['user_id']], 'avatars');
            if(!$avatars) $avatars = getUrl() . '/storage/moren/head.png';

            $jobInfo = Job::getFind(['id' => $info['job_id']]);

            $info['job_name']        = $jobInfo['name'];
            $info['project_id']      = $jobInfo['project_id'];
            $info['project_name']    = Project::getVal(['id' => $jobInfo['project_id']], 'name');
            $info['sex']             = $info['sex'] ? $sexs[$info['sex']] : '保密';
            $info['education']       = $edu[$info['education']];
            $info['jobs_status']     = $jobStatus[$info['jobs_status']];
            $info['user_avatars']    = $avatars;
            $info['is_set']          = $info['add_user_id'] == $this->user_id ? 1 : 0;
            $info['is_del']          = $info['add_user_id'] == $this->user_id ? 1 : 0;
            
            if($info['share_user_id']){
                $info['share_user_name'] = User::getVal(['id' => $info['share_user_id']], 'name');
            }else{
                $info['share_user_name'] = '';
            }
        }

        return Json::success('ok', $list, UserResume::getNum($where));
    }

    /**
     * 我的简历
     */
    public function getResumeMyList()
    {
        $page      = Request()->param('page', 1);
        $status    = Request()->param('status', 0);
        $sex       = Request()->param('sex', 0);
        $age       = Request()->param('age', '');
        $education = Request()->param('education', 0);
        $jobId     = Request()->param('job_id', 0);
        $projectId = Request()->param('project_id', 0);
        $name      = Request()->param('name', '');

        $where[] = ['r.user_id', '=', $this->user_id];
        $where[] = ['ur.is_staff', '=', 0];
        $where[] = ['ur.name', '<>', ''];

        if($status != 0){
            $where[] = ['r.status', '=', $status];
        }else{
            $where[] = ['r.status', 'in', [1,2,3,4,5,6,7,8,9]];
        }

        if(!empty($name)) $where[] = ['ur.name', 'like', '%' . $name . '%'];

        if($sex != 0) $where[] = ['ur.sex', '=', $sex];
        if($education != 0) $where[] = ['ur.education', '=', $education];
        if($jobId != 0) $where[] = ['ur.job_id', '=', $jobId];

        if($projectId != 0){
            $jobIds = Job::getCol(['project_id' => $projectId], 'id');
            $where[] = ['ur.job_id', 'in', $jobIds];
        }

        if(!empty($age)){
            list($ageLow, $ageHigh) = explode('-', $age);

            if($ageLow > 0) $where[]  = ['ur.age', '<=', $ageLow];
            if($ageHigh > 0) $where[] = ['ur.age', '>=', $ageHigh];
        }

        $field = [
            'ur.id', 
            'ur.name', 
            'ur.sex', 
            'ur.user_id', 
            'ur.share_user_id', 
            'ur.add_user_id', 
            'ur.job_id', 
            'ur.age', 
            'ur.education', 
            'ur.mobile', 
            'ur.wechat_no', 
            'ur.expect_jobs', 
            'ur.expect_city', 
            'ur.card_num', 
            'ur.wage', 
            'ur.address', 
            'r.remarks',
            'r.status', 
            'r.round', 
            'ur.round as round_now',
            'r.job_id as invite_job_id', 
            'r.project_id as invite_project_id', 
            'ur.jobs_status', 
            'ur.create_time'
        ];

        $list = ResumeRound::where($where)
            ->alias('r')
            ->join('user_resume ur', 'r.resume_id=ur.id')
            ->field($field)
            ->order('r.create_time DESC')
            ->page((int)$page, 20)
            ->select();
        
        if($list->isEmpty()) return Json::fail('暂无数据');

        $edu       = [0 => '其他', 1 => '小学', 2 => '初中', 3 => '高中', 4 => '大专', 5 => '本科', 6 => '硕士', 7 => '博士'];
        $sexs      = [1 => '男', 2 => '女'];
        $jobStatus = [1 => '在职', 2 => '离职'];

        foreach($list as &$info){
            $avatars = User::getVal(['id' => $info['user_id']], 'avatars');
            if(!$avatars) $avatars = getUrl() . '/storage/moren/head.png';

            $jobInfo = Job::getFind(['id' => $info['job_id']]);

            $inviteJobName     = Job::getVal(['id' => $info['invite_job_id']], 'name');
            $inviteProjectName = Project::getVal(['id' => $info['invite_project_id']], 'name');

            if($inviteJobName){
                $info['invite_job_name'] = $inviteJobName;
                if($inviteProjectName) $info['invite_job_name'] .= '(' . $inviteProjectName . ')';
            }else{
                $info['invite_job_name'] = '';
            }

            $info['job_name']        = $jobInfo['name'];
            $info['project_id']      = $jobInfo['project_id'];
            $info['project_name']    = Project::getVal(['id' => $jobInfo['project_id']], 'name');
            $info['sex']             = $info['sex'] ? $sexs[$info['sex']] : '保密';
            $info['education']       = $edu[$info['education']];
            $info['jobs_status']     = $jobStatus[$info['jobs_status']];
            $info['user_avatars']    = $avatars;
            $info['is_set']          = $info['add_user_id'] == $this->user_id ? 1 : 0;
            $info['is_del']          = $info['add_user_id'] == $this->user_id ? 1 : 0;

            if($info['share_user_id']){
                $info['share_user_name'] = User::getVal(['id' => $info['share_user_id']], 'name');
            }else{
                $info['share_user_name'] = '';
            }
        }

        $num = ResumeRound::where($where)
            ->alias('r')
            ->join('user_resume ur', 'r.resume_id=ur.id')
            ->count();

        return Json::success('ok', $list, $num);
    }

    /**
     * 已邀约简历
     */
    public function getInviteList()
    {
        $page      = Request()->param('page', 1);
        $status    = Request()->param('status', 0);
        $sex       = Request()->param('sex', 0);
        $age       = Request()->param('age', '');
        $education = Request()->param('education', 0);
        $jobId     = Request()->param('job_id', 0);
        $projectId = Request()->param('project_id', 0);
        $faceTime  = Request()->param('face_time', '');
        $name      = Request()->param('name', '');

        if($status != 0){
            $where[] = ['r.status', '=', $status];
        }else{
            $where[] = ['r.status', 'in', [2,3,4,5,6,7,8,9]];
        }

        if($sex != 0) $where[]       = ['ur.sex', '=', $sex];
        if(!empty($name)) $where[]   = ['ur.name', 'like', '%' . $name . '%'];
        if($education != 0) $where[] = ['ur.education', '=', $education];

        if($projectId != 0 && $jobId == 0){
            $jobIds = Job::getCol(['project_id' => $projectId], 'id');
            $where[] = ['r.job_id', 'in', $jobIds];
        }else if($jobId != 0){
            $where[] = ['r.job_id', '=', $jobId];
        }

        if(!empty($age)){
            list($ageLow, $ageHigh) = explode('-', $age);

            if($ageLow > 0) $where[]  = ['ur.age', '<=', $ageLow];
            if($ageHigh > 0) $where[] = ['ur.age', '>=', $ageHigh];
        }

        if(!empty($faceTime)){
            list($startTime, $endTime) = explode('~', $faceTime);

            $where[] = ['r.face_time', 'between', [strtotime($startTime), strtotime($endTime) + 86399]];
        }

        $field = [
            'ur.id', 
            'r.user_id as claim_user_id', 
            'ur.name', 
            'ur.sex', 
            'ur.user_id', 
            'ur.share_user_id', 
            'r.job_id', 
            'ur.age', 
            'ur.education', 
            'ur.mobile', 
            'ur.wechat_no', 
            'ur.expect_jobs',
            'ur.expect_city',
            'ur.card_num', 
            'ur.wage', 
            'ur.address', 
            'r.status', 
            'r.round', 
            'ur.round as round_now', 
            'ur.jobs_status', 
            'ur.create_time',
            'r.invite_time',
            'r.face_time',
            'r.join_time',
        ];

        $list = ResumeRound::where($where)
            ->alias('r')
            ->join('user_resume ur', 'r.resume_id=ur.id')
            ->field($field)
            ->order('r.status, r.invite_time DESC')
            ->page((int)$page, 20)
            ->select();
        
        if($list->isEmpty()) return Json::fail('暂无数据');

        $edu       = [0 => '其他', 1 => '小学', 2 => '初中', 3 => '高中', 4 => '大专', 5 => '本科', 6 => '硕士', 7 => '博士'];
        $sexs      = [1 => '男', 2 => '女'];
        $jobStatus = [1 => '在职', 2 => '离职'];

        foreach($list as &$info){
            $avatars = User::getVal(['id' => $info['user_id']], 'avatars');
            if(!$avatars) $avatars = getUrl() . '/storage/moren/head.png';

            $jobInfo = Job::getFind(['id' => $info['job_id']]);

            $info['job_name']     = $jobInfo['name'];
            $info['project_id']   = $jobInfo['project_id'];
            $info['project_name'] = Project::getVal(['id' => $jobInfo['project_id']], 'name');
            $info['sex']          = $info['sex'] ? $sexs[$info['sex']] : '保密';
            $info['education']    = $edu[$info['education']];
            $info['jobs_status']  = $jobStatus[$info['jobs_status']];
            $info['user_avatars'] = $avatars;
            $info['claim_name']   = User::getVal(['id' => $info['claim_user_id']], 'name');
            $info['invite_time']  = $info['invite_time'] ? date('Y-m-d H:i', $info['invite_time']) : '';
            $info['face_time']    = ResumeRecord::getVal(['resume_id' => $info['id'], 'status' => 2], 'face_time');
            $info['join_time']    = $info['join_time'] ? date('Y-m-d H:i', $info['join_time']) : '';

            if($info['share_user_id']){
                $info['share_user_name'] = User::getVal(['id' => $info['share_user_id']], 'name');
            }else{
                $info['share_user_name'] = '';
            }
        }

        $num = ResumeRound::where($where)
            ->alias('r')
            ->join('user_resume ur', 'r.resume_id=ur.id')
            ->count();

        return Json::success('ok', $list, $num);
    }

    /**
     * 获取简历状态数量
     */
    public function getResumeNum()
    {
        $type      = Request()->param('type', 0);
        $sex       = Request()->param('sex', 0);
        $age       = Request()->param('age', '');
        $education = Request()->param('education', 0);
        $jobId     = Request()->param('job_id', 0);
        $projectId = Request()->param('project_id', 0);
        $name      = Request()->param('name', '');

        if($sex != 0) $where[] = ['ur.sex', '=', $sex];
        if(!empty($name)) $where[] = ['ur.name', 'like', '%' . $name . '%'];
        if($education != 0) $where[] = ['ur.education', '=', $education];

        if($projectId != 0 && $jobId == 0){
            $jobIds = Job::getCol(['project_id' => $projectId], 'id');
            $where[] = ['r.job_id', 'in', $jobIds];
        }else if($jobId != 0){
            $where[] = ['r.job_id', '=', $jobId];
        }

        if(!empty($age)){
            list($ageLow, $ageHigh) = explode('-', $age);

            if($ageLow > 0) $where[]  = ['ur.age', '<=', $ageLow];
            if($ageHigh > 0) $where[] = ['ur.age', '>=', $ageHigh];
        }

        $where[] = ['ur.is_staff', '=', 0];

        if($type == 1){
            $where[] = ['r.user_id', '=', $this->user_id];
            $where[] = ['r.status', 'in', [1,2,3,4,5,6,7,8,9]];

            $backData = [
                [
                    'name'   => '全部',
                    'status' => 0,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '认领',
                    'status' => 1,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 1)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '邀约',
                    'status' => 2,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 2)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '通过',
                    'status' => 4,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 4)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '入职',
                    'status' => 5,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 5)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '未到面',
                    'status' => 6,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 6)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '未通过',
                    'status' => 7,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 7)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '未入职',
                    'status' => 8,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 8)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '离职',
                    'status' => 9,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 9)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
            ];
        }else{
            $backData = [
                [
                    'name'   => '全部',
                    'status' => 0,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where([['r.status', 'in', [2,3,4,5,6,7,8,9]]])
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '邀约',
                    'status' => 2,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 2)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '通过',
                    'status' => 4,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 4)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '入职',
                    'status' => 5,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 5)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '未到面',
                    'status' => 6,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 6)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '未通过',
                    'status' => 7,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 7)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '未入职',
                    'status' => 8,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 8)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
                [
                    'name'   => '离职',
                    'status' => 9,
                    'count'  => ResumeRound::where($where)
                        ->alias('r')
                        ->where('r.status', 9)
                        ->join('user_resume ur', 'r.resume_id=ur.id')
                        ->count(),
                ],
            ];
        }

        return Json::success('ok', $backData);
    }

    /**
     * 简历状态修改
     */
    public function setResumeStatus()
    {
        $resumeId  = Request()->param('resume_id', 0);
        $round     = Request()->param('round', 0);
        $type      = Request()->param('type', -1);
        $remarks   = Request()->param('remarks', '');
        $projectId = Request()->param('project_id', 0);
        $jobId     = Request()->param('job_id', 0);
        $faceTime  = Request()->param('face_time', '');
        $joinTime  = Request()->param('join_time', '');
        $quitTime  = Request()->param('quit_time', '');
        $channel   = Request()->param('channel', 0);
        $userId    = $this->user_id;

        $resumeInfo = UserResume::getFind(['id' => $resumeId]);
        if(!$resumeInfo) return Json::fail('简历不存在');
        if($type == 1 && $resumeInfo['claim_user_id'] != 0) return Json::fail('简历已被认领');
        if($type == 0 && $resumeInfo['status'] > 1) return Json::fail('邀约后的简历不能退回');

        /** 操作类型：1=认领，2=邀约，3=到面，4=通过，5=入职，6=未到面，7=未通过，8=未入职，9=离职, 0=退回 */
        $status = [1 => '认领', 2 => '邀约', 3 => '到面', 4 => '通过', 5 => '入职', 6 => '未到面', 7 => '未通过', 8 => '未入职', 9 => '离职', 10 => '退回'];

        $roundData['status'] = $type;
        $roundData['round']  = $resumeInfo['round'];

        $recordData['user_id']     = $userId;
        $recordData['resume_id']   = $resumeId;
        $recordData['remarks']     = $remarks;
        $recordData['status']      = $type;
        $recordData['round']       = $resumeInfo['round'];
        $recordData['status_time'] = time();

        switch ($type) {
            case 1:
                $roundData['resume_id']  = $resumeId;
                $roundData['user_id']    = $userId;
                $roundData['claim_time'] = time();
                break;
            case 2:
                $roundData['invite_time'] = time();

                $roundData['project_id'] = $projectId;
                $roundData['job_id']     = $jobId;
                $roundData['channel']    = $channel;

                if(!empty($faceTime)){
                    list($days, $times1, $times2) = explode('/', $faceTime);
                    $faceTimes = $days . ' ' . $times1 . '~' . $days . ' ' . $times2;
                }else{
                    $faceTimes = '';
                }

                $roundData['face_time'] = strtotime($days . ' ' . $times1);
                
                $recordData['face_time'] = $faceTimes;
                break;
            case 3:
                // $roundData['face_time'] = time();
                break;
            case 4:
                $roundData['pass_time'] = time();
                break;
            case 5:
                $roundData['join_time'] = strtotime($joinTime);

                $recordData['status_time'] = strtotime($joinTime);
                break;
            case 6:
                # code...
                break;
            case 7:
                # code...
                break;
            case 8:
                # code...
                break;
            case 9:
                $roundData['quit_time'] = $quitTime;

                $recordData['status_time'] = strtotime($quitTime);
                break;
            // default:
            //     if(ResumeRound::where(['user_id' => $userId, 'status' => 10])->whereDay('create_time')->count() > 0) return Json::fail('每天只能退回一次');
            //     break;
        }

        self::beginTrans();
        try {
            if($type == 1){
                $resumeRoundFlag = ResumeRound::add($roundData);

                /** 简历更新认领人 */
                UserResume::edit(['id' => $resumeId, 'claim_user_id' => $userId]);
            }else{
                $resumeRoundFlag = ResumeRound::editWhere($roundData, ['resume_id' => $resumeId, 'round' => $round]);
            }

            if($resumeRoundFlag === false) throw new Exception($status[$type] . '失败');

            if($type == 9 || $type == 10){
                UserResume::setIncField(['id' => $resumeId], 'round');
                UserResume::edit(['id' => $resumeId, 'claim_user_id' => 0]);
            }

            $resumeRecordFlag = ResumeRecord::add($recordData);
            if($resumeRecordFlag === false) throw new Exception('添加操作记录失败');

            switch ($type) {
                case 2:
                    $inviteWhere[] = ['user_id', '=', $userId];
                    $inviteWhere[] = ['stage', '=', OkrRecord::getStage()];

                    /** 增加邀约人数 */
                    OkrRecord::setIncField($inviteWhere, 'invite_num_reality');

                    /** 更新计算OKR分数 */
                    OkrRecord::setOkrFrac($userId, 2);
                    break;
                case 4:
                    $inviteWhere[] = ['user_id', '=', $userId];
                    $inviteWhere[] = ['stage', '=', OkrRecord::getStage()];

                    /** 增加到面人数 */
                    OkrRecord::setIncField($inviteWhere, 'face_num_reality');

                    /** 更新计算OKR分数 */
                    OkrRecord::setOkrFrac($userId, 3);


                    /** 增加通过人数 */
                    OkrRecord::setIncField($inviteWhere, 'pass_num_reality');

                    /** 更新计算OKR分数 */
                    OkrRecord::setOkrFrac($userId, 4);

                    /** 添加弹幕消息 */
                    $content = User::getVal(['id' => $userId], 'name') . '邀约的' . User::getVal(['id' => $resumeInfo['user_id']], 'name') . '面试通过';
                    Message::setMessage(0, $resumeRecordFlag['id'], 2, $content);
                    break;
            }

            self::commitTrans();
        }catch(\Exception $e){
            self::rollbackTrans();
            return Json::fail($e->getMessage());
        }

        return Json::success($status[$type] . '成功');
    }

    /**
     * 获取简历操作记录
     */
    public function getResumeRecord()
    {
        $resumeId = Request()->param('resume_id', 0);

        $where[] = ['resume_id', '=', $resumeId];

        $list = ResumeRecord::getList($where, 0, 0, 0, '*', 'id DESC');
        if($list === false) return Json::fail('暂无数据');

        $status = [1 => '认领', 2 => '邀约', 3 => '到面', 4 => '通过', 5 => '入职', 6 => '未到面', 7 => '未通过', 8 => '未入职', 9 => '离职', 10 => '退回'];

        foreach($list as &$info){
            $jobId = ResumeRound::getVal(['id' => $info['resume_id'], 'round' => $info['round']], 'job_id');

            $info['user_name']   = User::getVal(['id' => $info['user_id']], 'name');
            $info['type']        = $status[$info['status']];
            $info['job_name']    = $jobId ? Job::getVal(['id' => $jobId], 'name') : '';
            $info['face_time']   = $info['face_time'] ? $info['face_time'] : '';
            $info['status_time'] = $info['status_time'] ? date('Y-m-d H:i:s', $info['status_time']) : '';

            unset($info['user_id']);
            unset($info['resume_id']);
            unset($info['job_id']);
        }

        return Json::success('ok', $list);
    }

    /**
     * 上传简历
     */
    public function setResume()
    {
        $projectId = Request()->param('project_id', 0);
        $param     = Request()->param();

        if($projectId != 0){
            $projectInfo = Project::getFind(['id' => $projectId]);
            if(!$projectInfo || empty($projectInfo['resume_field_ids'])) return Json::fail('项目不存在');

            $resumeField = ResumeFieldDepot::getList([['id', 'in', explode(',', $projectInfo['resume_field_ids'])], ['type_use', 'in', [1,3]]], 0);

            foreach($resumeField as $fieldInfo){
                if(isset($param[$fieldInfo['key']])){
                    if(empty($param[$fieldInfo['key']])) return Json::fail($fieldInfo['label'] . '不能为空');
                }else{
                    return Json::fail($fieldInfo['label'] . '必传');
                }
            }
        }

        $param['claim_user_id'] = isset($param['status']) && $param['status'] ? $this->user_id : 0;
        if(isset($param['wage'])) list($param['wage_low'], $param['wage_high']) = explode('-', $param['wage']);
        $param['add_user_id'] = $this->user_id;

        $flag = UserResume::add($param);
        if($flag === false) return Json::fail('上传失败');

        /** 新增学校信息 */
        if(isset($param['school_name'])
            || isset($param['speciality']) 
            || isset($param['certificate_no'])
        ){
            $schoolData = [
                'resume_id'      => $flag['id'],
                'school'         => isset($param['school_name']) ? $param['school_name'] : '',
                'speciality'     => isset($param['speciality']) ? $param['speciality'] : '',
                'education'      => isset($param['education']) ? $param['education'] : '',
                'certificate_no' => isset($param['certificate_no']) ? $param['certificate_no'] : '',
            ];

            ResumeEducation::add($schoolData);
        }


        /** 我的简历上传默认已认领状态 */
        if($param['claim_user_id'] != 0){
            ResumeRound::add([
                'user_id'     => $this->user_id,
                'resume_id'   => $flag['id'],
                'status'      => 1,
                'round'       => 1,
                'status_time' => time(),
            ]);
        }
        return Json::success('上传成功');
    }

    /**
     * 编辑简历基本信息
     */
    public function setResumeEdit()
    {
        
        $param['id']          = Request()->param('id', 0);
        $param['name']        = Request()->param('name', '');
        $param['sex']         = Request()->param('sex', 0);
        $param['age']         = Request()->param('age', 0);
        $param['education']   = Request()->param('education', 0);
        $param['mobile']      = Request()->param('mobile', '');
        $param['expect_jobs'] = Request()->param('expect_jobs', '');
        $param['expect_city'] = Request()->param('expect_city', '');
        $param['wage']        = Request()->param('wage', '');
        $param['job_num']     = Request()->param('job_num', 0);

        if(!empty($param['wage'])) list($param['wage_low'], $param['wage_high']) = explode('-', $param['wage']);
        if(isset($param['wage_high']) && $param['wage_high'] == '以上') $param['wage_high'] = 0;

        $flag = UserResume::edit($param);
        if($flag === false) return Json::fail();
        return Json::success();
    }

    /**
     * 修改面试时间
     */
    public function setRecordFaceTime()
    {
        $recordId = Request()->param('record_id', 0);
        $faceTime = Request()->param('face_time', '');
        if($recordId == 0) return Json::fail('记录Id不能为空'); 
        if(empty($faceTime)) return Json::fail('面试时间不能为空');

        $recordInfo = ResumeRecord::getFind(['id' => $recordId]);

        list($days, $times1, $times2) = explode('/', $faceTime);
        $faceTimes = $days . ' ' . $times1 . '~' . $days . ' ' . $times2;

        $flag = ResumeRecord::edit(['id' => $recordId, 'face_time' => $faceTimes]);
        if(!$flag) return Json::fail();

        ResumeRound::editWhere(['face_time' => strtotime($days . ' ' . $times1)], ['resume_id' => $recordInfo['resume_id'], 'round' => $recordInfo['round']]);
        return Json::success();
    }

    /**
     * 删除简历
     */
    public function delResume()
    {
        $id = Request()->param('id', 0);
        if($id == 0) return Json::fail('参数错误');

        $flag = UserResume::destroy($id);
        if(!$flag) return Json::fail();
        return Json::success();
    }

    /**
     * 批量导入简历
     */
    public function setResumeIn()
    {
        ini_set('memory_limit', '1024M');
        set_time_limit(0);

        if($this->request->isPost()){
            header("Content-type:text/html;charset=utf-8");

            $file = $_FILES['excel'];

            /** 截取文件的后缀名，转化成小写 */
            $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

            if($extension == "xlsx"){
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            }else if($extension == "xls"){
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            }else{
                return Json::fail('请上传Excel文件');
            }

            $objContent   = $objReader->load($file['tmp_name']);
            $sheetContent = $objContent->getSheet(0)->toArray();
            
            /** 删除第一行标题 */
            unset($sheetContent[0]);

            $education = [0 => '其他', 1 => '小学', 2 => '初中', 3 => '高中', 4 => '专科', 5 => '本科', 6 => '硕士', 7 => '博士'];

            /** 后面写逻辑代码 */
            foreach($sheetContent as $info){
                $data['name']        = !empty($info[0]) ? $info[0] : '';
                $data['mobile']      = !empty($info[1]) ? $info[1] : '';
                $data['sex']         = $info[2] == '男' ? 1 : 2;
                $data['age']         = !empty($info[3]) ? $info[3] : rand(699379200, 1014912000);
                $data['residence']   = !empty($info[4]) ? $info[4] : '';
                $data['address']     = !empty($info[5]) ? $info[5] : '';
                $data['card_num']    = !empty($info[6]) ? $info[6] : '';
                $data['source']      = 3;
                $data['education']   = !empty($info[9]) ? (in_array($info[9], $education) ? array_search($info[9], $education) : 0) : 0;
                $data['expect_jobs'] = !empty($info[11]) ? $info[11] : '';
                $data['expect_city'] = !empty($info[12]) ? $info[12] : '';
                $data['add_user_id'] = $this->user_id;

                $flag = UserResume::add($data);

                if($flag){
                    $eduData['resume_id']  = $flag['id'];
                    $eduData['school']     = !empty($info[7]) ? $info[7] : '';
                    $eduData['speciality'] = !empty($info[8]) ? $info[8] : 00;
                    $eduData['education']  = !empty($info[9]) ? (in_array($info[9], $education) ? array_search($info[9], $education) : 0) : 0;
                    $eduData['end_time']   = !empty($info[10]) ? strtotime($info[10]) : 0;

                    ResumeEducation::add($eduData);
                }
            }

            return Json::success('导入成功');
        }
    }

    /**
     * 简历详情
     */
    public function getUserResumeShow()
    {
        $userId = Request()->param('user_id', 0);
        $info = UserResume::getResumeShow($userId);
        if(!$info) return Json::fail();

        $info['company_name'] = UserCompany::getVal(['id' => $info['company_id']], 'name');
        return Json::success('ok', $info);
    }

    /**
     * 我的简历-备注
     */
    public function setResumeRemarks()
    {
        $resumeId = Request()->param('resume_id', 0);
        $round    = Request()->param('round', 0);
        $remarks  = Request()->param('remarks', '');
        if($resumeId == 0 || $round == 0) return Json::fail('参数错误');
        if(empty($remarks)) return Json::fail('备注不能为空');

        $flag = ResumeRound::editWhere(['remarks' => $remarks], ['resume_id' => $resumeId, 'round' => $round]);
        if(!$flag) return Json::fail();
        return Json::success();
    }

    /**
     * 渠道列表
     */
    public function getChannelList()
    {
        return Json::success('ok', Choice::channel());
    }



    /**
     * 已邀约数据导出Excel
     */
    public function setResumeInviteOut()
    {
        $status    = Request()->param('status', 0);
        $sex       = Request()->param('sex', 0);
        $age       = Request()->param('age', '');
        $education = Request()->param('education', 0);
        $jobId     = Request()->param('job_id', 0);
        $projectId = Request()->param('project_id', 0);
        $faceTime  = Request()->param('face_time', '');

        if($projectId == 0) return Json::success('项目不能为空');

        $where = [];

        if($status != 0){
            $where[] = ['r.status', '=', $status];
        }else{
            $where[] = ['r.status', '>=', 2];
        }

        if($sex != 0) $where[] = ['ur.sex', '=', $sex];
        if($education != 0) $where[] = ['ur.education', '=', $education];
        if($jobId != 0) $where[] = ['r.job_id', '=', $jobId];

        if($projectId != 0){
            $jobIds = Job::getCol(['project_id' => $projectId], 'id');
            $where[] = ['r.job_id', 'in', $jobIds];
        }

        if(!empty($age)){
            list($ageLow, $ageHigh) = explode('-', $age);

            if($ageLow > 0) $where[]  = ['ur.age', '<=', $ageLow];
            if($ageHigh > 0) $where[] = ['ur.age', '>=', $ageHigh];
        }

        if(!empty($faceTime)){
            list($startTime, $endTime) = explode('~', $faceTime);

            $where[] = ['r.face_time', 'between', [strtotime($startTime), strtotime($endTime) + 86399]];
        }

        $list = ResumeRound::where($where)
            // ->whereDay('r.invite_time')
            ->alias('r')
            ->join('user_resume ur', 'r.resume_id=ur.id')
            ->order('ur.create_time DESC')
            ->select();

        if($list->isEmpty()) return Json::fail('暂无数据');

        $edu = [0 => '其他', 1 => '小学', 2 => '初中', 3 => '高中', 4 => '大专', 5 => '本科', 6 => '硕士', 7 => '博士'];
        $sex = [1 => '男', 2 => '女'];

        $projectInfo = Project::getFind(['id' => $projectId]);
        if(!$projectInfo) return Json::fail('项目不存在');

        $resumeFieldList = ResumeFieldDepot::where([['id', 'in', explode(',', $projectInfo['resume_field_ids'])]])
            ->whereOr(['type_use' => 4])
            ->field('label, key')
            ->order('sort')
            ->select()
            ->toArray();

        /** 实例化 */
        $objExcel = new \PHPExcel();

        /** 设置文档属性 */
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        /** 设置内容 */
        $objActSheet = $objExcel->getActiveSheet();

        $number = count($resumeFieldList);
        $letter = getLetter($number);

        for($i = 0; $i < $number; $i++) $resumeFieldList[$i]['sort'] = $letter[$i];

        $arrHeader = array_column($resumeFieldList, 'label');

        /** 填充表头信息 */
        $lenth = count($arrHeader);
        for($i = 0; $i < $lenth; $i++) $objActSheet->setCellValue("$letter[$i]1", "$arrHeader[$i]");

        $objActSheet->getStyle('A1:' . $letter[count($arrHeader) - 1] . (count($list) + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);  /** 水平居中 */
        $objActSheet->getStyle('A1:' . $letter[count($arrHeader) - 1] . (count($list) + 1))->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);  /** 垂直居中 */

        $objActSheet->getDefaultColumnDimension()->setWidth(15);  /** 所有单元格（列）默认宽度 */

        /** 标题栏 */
        $objActSheet->getStyle('A1:' . $letter[count($arrHeader) - 1] . '1')->getFont()->setBold(true);  /** 加粗 */
        $objActSheet->getStyle('A1:' . $letter[count($arrHeader) - 1] . '1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);  /** 填充颜色 */
        $objActSheet->getStyle('A1:' . $letter[count($arrHeader) - 1] . '1')->getFill()->getStartColor()->setARGB('FFFFCC');  /** 设置填充颜色 */

        $objActSheet->getRowDimension('1')->setRowHeight(30);  /** 设置行高度 */

        /** 设置边框 */
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => PHPExcel_Style_Border::BORDER_THIN,  /** 细边框 */
                ),
            ),
        );
        $objActSheet->getStyle('A1:' . $letter[count($arrHeader) - 1] . (count($list) + 1))->applyFromArray($styleArray);

        /** 填充表格信息 */
        foreach($list as $k => $info){
            $k += 2;

            $jobInfo  = Job::getFind(['id' => $info['job_id']]);
            $eduInfo  = ResumeEducation::getFind(['resume_id' => $info['id']], '*', 'create_time DESC');

            foreach($resumeFieldList as $value){
                switch ($value['key']) {
                    case 'resume_id':  /** 人才编码 */
                        $objActSheet->setCellValue($value['sort'] . $k, $info['id']);  
                        break;
                    case 'company_name':  /** 公司名称 */
                        $objActSheet->setCellValue($value['sort'] . $k, Project::getVal(['id' => $jobInfo['project_id']], 'name'));
                        break;
                    case 'job_id':  /** 职位 */
                        $objActSheet->setCellValue($value['sort'] . $k, $jobInfo['name']);
                        break;
                    case 'face_time_M':
                        $objActSheet->setCellValue($value['sort'] . $k, date('n', $info['face_time']) . '月');
                        break;
                    case 'face_time_w':
                        $objActSheet->setCellValue($value['sort'] . $k, date('W', $info['face_time']) . '周');
                        break;
                    case 'face_time_D':
                        $objActSheet->setCellValue($value['sort'] . $k, date('Y/m/d', $info['face_time']));
                        break;
                    case 'claim_user_name':
                        $objActSheet->setCellValue($value['sort'] . $k, User::getVal(['id' => $info['claim_user_id']], 'name'));
                        break;
                    case 'channel':
                        $objActSheet->setCellValue($value['sort'] . $k, Choice::channel($info['channel']));
                        break;
                    case 'name':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['name']);
                        break;
                    case 'sex':
                        $objActSheet->setCellValue($value['sort'] . $k, Choice::sex($info['sex']));
                        break;
                    case 'age':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['age'] ? $info['age'] : '\\');
                        break;
                    case 'mobile':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['mobile']);
                        break;
                    case 'education':
                        $objActSheet->setCellValue($value['sort'] . $k, $edu[$info['education']]);
                        break;
                    case 'wechat_no':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['wechat_no']);
                        break;
                    case 'expect_jobs':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['expect_jobs']);
                        break;
                    case 'expect_city':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['expect_city']);
                        break;
                    case 'residence':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['residence']);
                        break;
                    case 'card_num':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['card_num']);
                        break;
                    case 'wage':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['wage']);
                        break;
                    case 'job_num':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['job_num']);
                        break;
                    case 'address':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['address']);
                        break;
                    case 'email':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['email']);
                        break;
                    case 'school_name':
                        $objActSheet->setCellValue($value['sort'] . $k, $eduInfo['school']);
                        break;
                    case 'speciality':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['speciality']);
                        break;
                    case 'job_name_old':
                        $objActSheet->setCellValue($value['sort'] . $k, '\\');
                        break;
                    case 'typing_achievement':
                        $objActSheet->setCellValue($value['sort'] . $k, '\\');
                        break;
                    case 'result_fst':
                        if(in_array($info['status'], [4,5])){
                            $resultFst = '是';
                        }else if(in_array($info['status'], [6,7, 8])){
                            $resultFst = '否';
                        }else{
                            $resultFst = '\\';
                        }

                        $objActSheet->setCellValue($value['sort'] . $k, $resultFst);
                        break;
                    case 'result_sec':
                        if(in_array($info['status'], [4,5])){
                            $resultFst = '是';
                        }else if(in_array($info['status'], [7, 8])){
                            $resultFst = '否';
                        }else if($info['status'] == 6){
                            $resultFst = '未到面';
                        }else{
                            $resultFst = '\\';
                        }

                        $objActSheet->setCellValue($value['sort'] . $k, $resultFst);
                        break;
                    case 'face_remarks':
                        $remarksList = ResumeRecord::getCol([['resume_id', '=', $info['resume_id']], ['round', '=', $info['round']], ['remarks', '<>', '']], 'remarks');

                        if($remarksList){
                            $remarks = implode(',', $remarksList);
                        }else{
                            $remarks = '\\';
                        }

                        $objActSheet->setCellValue($value['sort'] . $k, $remarks);
                        break;
                    case 'is_offer':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['status'] == 5 ? '是' : '\\');
                        break;
                    case 'join_time':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['join_time'] ? date('Y/m/d', $info['join_time']) : '\\');
                        break;
                    case 'join_status':
                        $objActSheet->setCellValue($value['sort'] . $k, $info['status'] == 5 ? '入职' : '\\');
                        break;
                    case 'join_remarks':
                        $objActSheet->setCellValue($value['sort'] . $k, '\\');
                        break;
                    case 'quit_time':
                        $objActSheet->setCellValue($value['sort'] . $k, '\\');
                        break;
                }

            }
 
            /** 表格高度 */
            $objActSheet->getRowDimension($k)->setRowHeight(30);
        }
 
        $outfile = "邀约数据-" . date('Y-m-d H:i:s', time()) . ".xlsx";

        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:attachment;filename="' . $outfile . '"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");

        $objWriter->save('php://output', true);
    }

    /**
     * 导入反馈结果Excel
     */
    public function setResumeInviteIn()
    {
        ini_set('memory_limit', '1024M');
        set_time_limit(0);

        if($this->request->isPost()){
            header("Content-type:text/html;charset=utf-8");

            $file = $_FILES['excel'];

            /** 截取文件的后缀名，转化成小写 */
            $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

            if($extension == "xlsx"){
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            }else if($extension == "xls"){
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            }else{
                return Json::fail('请上传Excel文件');
            }

            $objContent   = $objReader->load($file['tmp_name']);
            $sheetContent = $objContent->getSheet(0)->toArray();

            /** 保存第一行标题 */
            $headerArr = array_flip($sheetContent[0]);

            /** 删除第一行标题 */
            unset($sheetContent[0]);

            /** 后面写逻辑代码 */
            foreach($sheetContent as $key => $info){
                $resumeInfo = UserResume::alias('ur')
                    ->where(['ur.id' => $info[$headerArr['人才编码']], 'r.status' => 2])
                    ->field('r.id as round_id, ur.id, ur.round, ur.claim_user_id, r.status')
                    ->join('resume_round r', 'r.resume_id=ur.id')
                    ->find();

                if($resumeInfo['status'] == 2){
                    /** 是否通过 */
                    if(!empty($info[$headerArr['复试结果']]) && strstr($info[$headerArr['复试结果']], '是') != false){
                        ResumeRound::edit([
                            'id'          => $resumeInfo['round_id'],
                            'status'      => 4,
                            'pass_time'   => time(),
                        ]);

                        $addData = [
                            'user_id'     => $this->user_id,
                            'resume_id'   => $resumeInfo['id'],
                            'status'      => 4,
                            'round'       => $resumeInfo['round'],
                            'status_time' => time(),
                        ];

                        if(!empty($info[$headerArr['面试备注']])) $addData['remarks'] = $info[$headerArr['面试备注']];

                        ResumeRecord::add($addData);

                        $inviteWhere[] = ['user_id', '=', $resumeInfo['claim_user_id']];
                        $inviteWhere[] = ['stage', '=', OkrRecord::getStage()];

                        /** 增加到面人数 */
                        OkrRecord::setIncField($inviteWhere, 'face_num_reality');

                        /** 更新计算OKR分数 */
                        OkrRecord::setOkrFrac($resumeInfo['claim_user_id'], 3);

                        /** 增加通过人数 */
                        OkrRecord::setIncField($inviteWhere, 'pass_num_reality');

                        /** 更新计算OKR分数 */
                        OkrRecord::setOkrFrac($resumeInfo['claim_user_id'], 4);
                    }else if(!empty($info[$headerArr['复试结果']]) && strstr($info[$headerArr['复试结果']], '否') != false){
                        ResumeRound::edit([
                            'id'          => $resumeInfo['round_id'],
                            'status'      => 7,
                            'pass_time'   => time(),
                        ]);

                        $addData = [
                            'user_id'     => $this->user_id,
                            'resume_id'   => $resumeInfo['id'],
                            'status'      => 7,
                            'round'       => $resumeInfo['round'],
                            'status_time' => time(),
                        ];

                        if(!empty($info[$headerArr['面试备注']])) $addData['remarks'] = $info[$headerArr['面试备注']];

                        ResumeRecord::add($addData);
                    }else if(!empty($info[$headerArr['复试结果']]) && strstr($info[$headerArr['复试结果']], '未到面') != false){
                        ResumeRound::edit([
                            'id'          => $resumeInfo['round_id'],
                            'status'      => 6,
                            'pass_time'   => time(),
                        ]);

                        $addData = [
                            'user_id'     => $this->user_id,
                            'resume_id'   => $resumeInfo['id'],
                            'status'      => 6,
                            'round'       => $resumeInfo['round'],
                            'status_time' => time(),
                        ];

                        if(!empty($info[$headerArr['面试备注']])) $addData['remarks'] = $info[$headerArr['面试备注']];

                        ResumeRecord::add($addData);
                    }
                    
                    /** 是否入职 */
                    if(!empty($info[$headerArr['是否接受offer']]) && strstr($info[$headerArr['是否接受offer']], '是') != false){
                        ResumeRound::edit([
                            'id'          => $resumeInfo['round_id'],
                            'status'      => 5,
                            'join_time'   => strtotime($info[$headerArr['入职时间']]) ? strtotime($info[$headerArr['入职时间']]) : time(),
                        ]);

                        ResumeRecord::add([
                            'user_id'     => $this->user_id,
                            'resume_id'   => $resumeInfo['id'],
                            'status'      => 5,
                            'round'       => $resumeInfo['round'],
                            'status_time' => strtotime($info[$headerArr['入职时间']]) ? strtotime($info[$headerArr['入职时间']]) : time(),
                        ]);
                    }else if(!empty($info[$headerArr['是否接受offer']]) && strstr($info[$headerArr['是否接受offer']], '否') != false){
                        ResumeRound::edit([
                            'id'          => $resumeInfo['round_id'],
                            'status'      => 8,
                            'join_time'   => strtotime($info[$headerArr['入职时间']]) ? strtotime($info[$headerArr['入职时间']]) : time(),
                        ]);

                        ResumeRecord::add([
                            'user_id'     => $this->user_id,
                            'resume_id'   => $resumeInfo['id'],
                            'status'      => 8,
                            'round'       => $resumeInfo['round'],
                            'status_time' => strtotime($info[$headerArr['入职时间']]) ? strtotime($info[$headerArr['入职时间']]) : time(),
                        ]);
                    }
                }
            }

            return Json::success('上传成功');
        }
    }





    /** 识别简历 */
    public function setDiscernResume()
    {
        $param = input('');
        if(empty($param['resume_file']) || empty($param['resume_name'])) return Json::fail('简历不能为空');

        $resumeFile = explode(';base64,', $param['resume_file'])[1];

        // 去识别附件简历，保存简历信息
        $resumeAllData = $this->resumeAnalysis($resumeFile, $param['resume_name']);
        $resumeAllData = json_decode($resumeAllData, true);

        if(isset($resumeAllData['errorcode']) && $resumeAllData['errorcode'] == 0){
            $resumeData = $resumeAllData['parsing_result'];

            switch ($resumeData['basic_info']['gender']){
                case '男': $sex = 1; break;
                case '女': $sex = 2; break;
                default: $sex = 0; break;
            }

            /** 新增教育经历 */
            // $educationList = [];
            // foreach($resumeData['education_experience'] as $educationInfo){
            //     $educationInfo = [
            //         'school'      => $educationInfo['school_name'],  /** 学校名称 */
            //         'education'   => $educationInfo['degree'],  /** 学历 */
            //         'speciality'  => $educationInfo['major'],  /** 专业 */
            //         'start_time'  => $educationInfo['start_time_year'] . '-' . $educationInfo['start_time_month'],  /** 开始时间 */
            //         'end_time'    => $educationInfo['end_time_year'] . '-' . $educationInfo['end_time_month'],  /** 结束时间 */
            //     ];

            //     $educationList[] = $educationInfo;
            // }
            
            /** 新增工作经历 */
            // $workList = [];
            // foreach($resumeData['work_experience'] as $workInfo){
            //     $workInfo = [
            //         'company_name'     => $workInfo['company_name'],  /** 公司名称 */
            //         'jobs'             => $workInfo['job_title'],  /** 职位名称 */
            //         'start_time'       => $workInfo['start_time_year'] . '-' . $workInfo['start_time_month'],  /** 开始时间 */
            //         'end_time'         => $workInfo['start_time_year'] . '-' . $workInfo['start_time_month'],  /** 结束时间 */
            //         'industry'         => $workInfo['industry'],  /** 公司性质 */
            //     ];

            //     $workList[] = $workInfo;
            // }

            $backData = [
                'name'                 => $resumeData['basic_info']['name'],  /** 姓名 */
                'sex'                  => $sex,  /** 性别 */
                'birthday'             => $resumeData['basic_info']['date_of_birth'],  /** 出生年月日 */
                // 'job_time'             => $resumeData['basic_info']['work_start_year'],  /** 参加工作时间 */
                // 'lives_city'           => $resumeData['basic_info']['detailed_location'],  /** 现居城市 */
                'registered_residence' => $resumeData['basic_info']['birthplace'],  /** 户口所在地(籍贯) */
                // 'wechat'               => $resumeData['contact_info']['wechat'],  /** 微信号 */
                'mobile'               => $resumeData['contact_info']['phone_number'],  /** 手机号 */
                // 'email'                => $resumeData['contact_info']['email'],  /** 邮箱 */
                'expect_jobs'          => $resumeData['basic_info']['desired_position'],  /** 期望职位 */
                // 'expect_industry'      => $resumeData['basic_info']['desired_industry'],  /** 期望行业 */
                // 'expect_city'          => $resumeData['basic_info']['expect_location'],  /** 期望城市 */
                'wage'                 => $resumeData['basic_info']['desired_salary'],  /** 期望薪资 */
                // 'work_nature'          => '全职',  /** 期望工作性质（全职、兼职） */
                // 'job_seeker_identity'  => '',  /** 求职者身份（1=学生，2=职场人） */
                // 'job_status'           => 1,  /** 求职状态（1=离职-随时到岗，2=在职-暂不考虑，3=在职-考虑机会，4=在职-月内到岗）当求职者身份是1时，直接填0 */
                // 'self_evaluate'        => $resumeData['others']['self_evaluation'],  /** 自我评价 */
                // 'vocational_skill'     => empty($resumeData['others']['skills'])?'':implode(',', $resumeData['others']['skills']),  /** 职位技能 */
                // 'credentials'          => empty($resumeData['others']['certificate'])?'':implode(',', $resumeData['others']['certificate']),  /** 资格证书 */
                // 'education_list'       => $educationList,
                // 'work_list'            => $workList,
            ];
        }

        return Json::success('ok', $backData);
    }

    /** 简历解析 */
    private function resumeAnalysis($file, $file_name)
    {
        $url = "http://api.xiaoxizn.com/v1/parser/parse_base?avatar=1&handle_image=1&rawtext=1&parse_mode=general"; //支持图片解析，提取简历头像，提取简历原文本，且使用普通解析模式

        $post_data = array(
            "resume_base" => $file,
            "file_name"   => $file_name
        );

        $post_data_string = json_encode($post_data);

        $header_data = array(
            'Content-Type: application/json',
            'id: 694dc9f0-cd9c-11eb-bf02-a7ee95e0630d', // 用户ID
            'secret: c7fb72d9-8de5-4c80-bb47-0c67c77b660c' // 用户密匙
        );

        $ch = curl_init();
        curl_setopt($ch , CURLOPT_URL , $url);
        curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch , CURLOPT_POST, 1);
        curl_setopt($ch , CURLOPT_POSTFIELDS, $post_data_string);
        curl_setopt($ch , CURLOPT_HTTPHEADER, $header_data);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

    /**
     * 简历库列表
     */
    public function getResumeFieldList()
    {
        return Json::success('ok', ResumeFieldDepot::getList([['type_use', 'in', [1,3]]], 0, 0, 0, 'id, label'));
    }

    /**
     * 项目的简历字段
     */
    public function getProjectToResumeField()
    {
        $projectId = Request()->param('project_id', 0);
        if($projectId == 0) return Json::fail('项目ID不能为空');

        $projectInfo = Project::getFind(['id' => $projectId]);
        if(!$projectInfo) return Json::fail('暂无数据');

        $list = ResumeFieldDepot::getList([['id', 'in', explode(',', $projectInfo['resume_field_ids'])], ['type_use', 'in', [1,3]]], 0);
        if(!$list) return Json::fail('暂无数据');

        foreach($list as &$info){
            if($info['options_type'] != 0){
                switch ($info['key']) {
                    case 'job_id':
                        $jobList = Job::getList(['is_show' => 1, 'status' => 1, 'project_id' => $projectId], 0, 0, 0, 'id, name');
                        $jobList = $jobList->toArray();

                        if(!$jobList){
                            $info['options'] = '';
                        }else{
                            $keys   = array_column($jobList, 'id');
                            $values = array_column($jobList, 'name');

                            $info['options'] = array_combine($keys, $values);
                        }
                        break;
                    default:
                        $info['options'] = '';
                        break;
                }

            }else if(!empty($info['options'])){
                $info['options'] = json_decode($info['options'], true);
            }else{
                $info['options'] = '';
            }
        }

        return Json::success('ok', $list);
    }



    /**
     * 新增简历外链
     */
    public function addResumeHref()
    {
        $param['name']       = Request()->param('name', '');
        $param['project_id'] = Request()->param('project_id', 0);

        $flag = ResumeHref::add($param);

        if(!$flag) return Json::fail();
        return Json::success();
    }

    /**
     * 外链简历新增
     */
    public function setResumeHref()
    {
        $projectId = Request()->param('project_id', 0);
        $param     = Request()->param();

        if($projectId != 0){
            $projectInfo = Project::getFind(['id' => $projectId]);
            if(!$projectInfo || empty($projectInfo['resume_field_ids'])) return Json::fail('项目不存在');

            $resumeField = ResumeFieldDepot::getList([['id', 'in', explode(',', $projectInfo['resume_field_ids'])], ['type_use', 'in', [1,3]]], 0);

            foreach($resumeField as $fieldInfo){
                if(isset($param[$fieldInfo['key']])){
                    if(empty($param[$fieldInfo['key']])) return Json::fail($fieldInfo['label'] . '不能为空');
                }else{
                    return Json::fail($fieldInfo['label'] . '必传');
                }
            }
        }

        if(isset($param['wage'])) list($param['wage_low'], $param['wage_high']) = explode('-', $param['wage']);
        $param['add_user_id'] = $this->user_id;
        $param['source']      = 4;

        $flag = UserResume::add($param);
        if($flag === false) return Json::fail('上传失败');

        /** 新增学校信息 */
        if(isset($param['school_name'])
            || isset($param['speciality']) 
            || isset($param['certificate_no'])
        ){
            $schoolData = [
                'resume_id'      => $flag['id'],
                'school'         => isset($param['school_name']) ? $param['school_name'] : '',
                'speciality'     => isset($param['speciality']) ? $param['speciality'] : '',
                'education'      => isset($param['education']) ? $param['education'] : '',
                'certificate_no' => isset($param['certificate_no']) ? $param['certificate_no'] : '',
            ];

            ResumeEducation::add($schoolData);
        }

        return Json::success('上传成功');
    }
}